/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Slave;

import Core.MessageBuilder;
import Core.ReaderThread;
import Core.WriterThread;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

/**
 *
 * @author mrbao
 */
public class SlaveClient {

    private SocketConnection socketConnection;
    private String host;
    private int port;
    private OutputStream out;
    private InputStream in;
    private ReaderThread readerThread;
    private WriterThread writerThread;

    public SlaveClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private void Connect() {
        try {
            socketConnection = (SocketConnection) Connector.open("socket://" + host + ":" + port);
            out = socketConnection.openOutputStream();
            in = socketConnection.openInputStream();
            readerThread = new ReaderThread(in);
            writerThread = new WriterThread(out);
        } catch (Exception e) {
        }
    }

    public ReaderThread GetReaderThread() {
        return readerThread;
    }

    public void Login(String username, String password, boolean invisible) {
        if (socketConnection == null) {
            Connect();
        }
        writerThread.QueueMessage(MessageBuilder.BuildLogInMessage(username, password, invisible));
    }

    public void SendTextMessage(String to, String message) {
        writerThread.QueueMessage(MessageBuilder.BuildSendTextMessage(to, message));
    }
}
